package com.wuyou.securitydemo.pwd;

import cn.hutool.json.JSONUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * CustomizedPasswordAuthenticationProvider
 *
 * @Date 2025/4/9 11:06
 * @Author 无忧
 */
@Slf4j
public class CustomizedPasswordAuthenticationProvider implements AuthenticationProvider {

    @Getter
    @Setter
    private UserDetailsService userDetailsService;

    @Getter
    @Setter
    private PasswordEncoder passwordEncoder;



    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取前端表单中输入后返回的用户名、密码、租户
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails == null) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        if(!passwordEncoder.matches(password, userDetails.getPassword())){
            throw new BadCredentialsException("用户名或密码错误");
        }
        Authentication passwordAuthentication = new CustomizedPasswordAuthenticationToken(userDetails, password, "deviceId");
        log.info("authenticate info ----> {}", JSONUtil.toJsonStr(authentication));

        return passwordAuthentication;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return CustomizedPasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }

    private String extractPwd(String encodePwd){
//        passwordEncoder.matches()
        return "";
    }
}
